package linkedlist.leetcode_21;


/**
 * 合并有序链表：迭代法
 */
public class Solution {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(6);
        ListNode l4 = new ListNode(9);
        l1.next=l2;
        l2.next=l3;
        l3.next=l4;
        l4.next=null;

        ListNode k1 = new ListNode(1);
        ListNode k2 = new ListNode(3);
        ListNode k3 = new ListNode(5);
        ListNode k4 = new ListNode(7);
        k1.next=k2;
        k2.next=k3;
        k3.next=k4;
        k4.next=null;
        Solution solution = new Solution();
        ListNode listNode = solution.mergeTwoLists2(l1, k1);
        printLinkedList(listNode);

    }
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        //利用哑节点，保存
        ListNode prevHead = new ListNode(-1);
        ListNode prevNode = prevHead;

        /**
         * 从两个链表的头开始进行比较，哪个节点值更小，就将prevNode指向它。
         */
        while(l1 != null && l2!=null){
            if (l1.val <= l2.val){
                prevNode.next = l1;
                l1 = l1.next;
            }else {
                prevNode.next = l2;
                l2 = l2.next;
            }
            prevNode = prevNode.next;
        }
        //将链表末尾指向位合并完的链表
        prevNode.next = l1 == null ? l2 : l1;
        //利用哑节点返回
        return prevHead.next;
    }
    public static void printLinkedList(ListNode node) {
        System.out.print("Linked List: ");
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
        System.out.println();
    }
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        if (l1 == null){
            return l2;
        }
        if (l2 == null){
            return l1;
        }
        if (l1.val <= l2.val){
            l1.next = mergeTwoLists2(l1.next,l2);
            return l1;
        }else {
            l2.next = mergeTwoLists2(l1, l2.next);
            return l2;
        }
    }
}
